﻿using CloudDcPc.Entity;
using CloudDcPc.util;
using CloudDcPc.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CloudDcPc
{
    /// <summary>
    /// OrderDlg.xaml 的交互逻辑
    /// </summary>
    public partial class OrderDlg : Window
    {
        private ObservableCollection<MyMenu> list_left = new ObservableCollection<MyMenu>();
        private ObservableCollection<MyMenu> list_right = new ObservableCollection<MyMenu>();
        public OrderDlg()
        {
            InitializeComponent();
            List<string> list_food_type = new List<string>();
            list_food_type = App.MyMenuBean.GetAllType();
            cb_food_type.ItemsSource = list_food_type;

            List<Tab> list_tab = App.TabBean.GetTabsByField("status","1");  
            cb_free_tab.ItemsSource = list_tab;

            ObservableCollection<Together> list_tg = App.TogetherBean.GetAllTogether();
            list_tg.Insert(0, new Together() { Name = "--无--" });
            cb_tg.ItemsSource = list_tg;
     

            list_left = App.TogetherBean.GetNotInMyMenu();
            //list_right = App.TogetherBean.GetInMyMenu(tg.Name);
            list_left_xml.ItemsSource = list_left;
            list_right_xml.ItemsSource = list_right;
        }
        private void cb_food_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            list_left = App.MyMenuBean.GetMyMenusByType(cb_food_type.SelectedItem + "");
            list_left_xml.ItemsSource = list_left;
        }
        private void btn_2right_Click(object sender, RoutedEventArgs e)
        {
            foreach (MyMenu item in list_left_xml.SelectedItems)
            {
                if (list_right.IndexOf(item) < 0)
                    list_right.Add(item);
            }
            list_left_xml.SelectedIndex = -1;
            refresh_sum();
        }

        private void btn_2left_Click(object sender, RoutedEventArgs e)
        {
            List<MyMenu> list = new List<MyMenu>();
            //遍历过程中不能修改故...
            foreach (MyMenu item in list_right_xml.SelectedItems)
            {
                list.Add(item);
            }
            foreach (MyMenu item in list)
            {
                list_right.Remove(item);
            }
            list_right_xml.SelectedIndex = -1;
            refresh_sum();
        }

        public void refresh_sum()
        {
            float sum = 0;
            foreach (MyMenu item in list_right)
            {
                try
                {
                    if (item.CountInTg == null)
                        return;
                    sum += float.Parse(item.CountInTg) * item.Price;
                }
                catch
                {
                    MessageBox.Show("数量只能为数字！");
                    txt_sum.Text = "0";
                }
            }
            txt_sum.Text = sum + "";
        }

        private void list_right_xml_KeyUp_1(object sender, KeyEventArgs e)
        {
            refresh_sum();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (list_right.Count == 0)
            {
                MessageBox.Show("还没有点任何菜品:(");
                return;
            }
            string tag = ((Button)sender).Tag.ToString();
            Together t = (Together)cb_tg.SelectedItem;
            string tg = "";
            float price = 0;
            if (t.Id != 0)
            {
                tg = t.Name;
                price = t.Price;
            }
            int tab_num = ((Tab)cb_free_tab.SelectedItem).Tab_num;
            int sizee;
            try
            {
                sizee = int.Parse(size.Text);
                if (sizee <= 0)
                    throw new Exception();
            }
            catch
            {
                MessageBox.Show("人数输入有误:(");
                return;
            }
            
            string timeStr = StringUtil.getFullTimeStr() + tab_num;
            int time_type = CommonUtil.getOrderTimeType();
            Order order = new Order()
            {
                Together_name = tg,
                Together_price = price,
                Order_num = timeStr,
                Size = sizee,
                Time_type = time_type,
                Tab_num = tab_num,
                User_num = App.user.User_num
            };



          //  App.OrderBean.AddOrder(order, list_right);    //FORDEBUG
           // if (App.OrderBean.AddOrder(order,list_right))
            //{
            double timeStamp = StringUtil.getNowTimeStamp();      
            string postStr = "", result = "";

            postStr += "{\"menulist\":[";
            foreach(MyMenu item in list_right)
            {
                if (item.Suffix=="" || item.Suffix==null)
                    item.Suffix = "null";
                postStr += "{\"suffix\":\"" + item.Suffix + "\",\"unit\":\"" + item.Unit + "\",\"foodnum\":\"" + item.Food_num + "\",\"type\":\"" + item.Type + "\",\"printpos\":" + item.Print_pos + ",\"piece\":\"" + item.CountInTg + "\",\"name\":\"" + item.Food_name + "\"},";
                            
            }
            postStr = postStr.TrimEnd(',');
            tg = tg==""?"null":tg;
            postStr += "],\"booktime\":0,\"time\":"+timeStamp+",\"togethername\":\""+tg+"\",\"vipnum\":\"null\",\"ordertype\":1,\"tabnum\":"+tab_num+",\"usernum\":\""+App.user.User_num+"\",\"note\":\"null\",\"timetype\":"+time_type+",\"size\":"+sizee+"}";
                    

                  
            try
            {
                PostSubmitter postSub = new PostSubmitter();
                result = postSub.SimplePost(postStr, "http://localhost:8080/OrderSystemServlet/OrderServlet");
            }
            catch
            {
                MessageBox.Show("点菜失败:(与服务器通讯发生错误" + postStr);
                return;
            }
            if (result.IndexOf('1') > 0)
            {
                MessageBox.Show("点菜成功:)");
                //this.DialogResult = true;
            }
            else if (result.IndexOf('3') > 0)
            {
                MessageBox.Show("菜单冲突:(");
                return;
            }else{
                MessageBox.Show("点菜失败:(");
                return;
            }
            try
                {
                    
                    
                    if (tag == "1")
                    {
                
                            List<int> t_list_tab_num = new List<int>();
                            t_list_tab_num.Add(order.Tab_num);

                            bool continued = true;
                            string order_id = "";
                            while (continued)
                            {   //防止服务器还没插入数据这边就读取
                                try
                                {
                                    order_id = App.OrderBean.GetOrderByOrderNum(order.Order_num).Id + "";
                                    continued = false;
                                }
                                catch (Exception eeee)
                                {
                                    continued = true;
                                    System.Threading.Thread.Sleep(500);
                                }
                            }

                            CheckOutDlg checkOut = new CheckOutDlg(order_id, t_list_tab_num);
                            checkOut.ShowDialog();
                    }
                    this.Close();
            }
            catch (Exception eee)
            {
                MessageBox.Show("失败！错误信息：\n" + eee.Message + "\n" + eee.Source + "\n" + eee.StackTrace, "提示");
                return;
            }

        
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
